<template>
    <div>
        <div class="conversation-bg">
            <title-bar title="群聊"></title-bar>
            <div v-for="item in messages">
                <message v-bind:item.sync="item"></message>
            </div>
            <div class="message-edit">
                <input class="message-input" placeholder="Type a message..." v-model="typingText" @keyup.enter="onSend" v-el:input />
            </div>
        </div>
    </div>
</template>

<script>
import _ from "lodash"
import { DEFAULT_AVATAR } from "../../const.js"
import Message from "../components/ConversationMessage"
import {imclient, MessageReciveEvent, IMClientInitEvent} from "../../assembly"
import {Realtime, TextMessage} from 'leancloud-realtime'
import EventEmitter from "../../src/common/EventEmitter"
import Toast from "../components/Toast/index.js"
import {UserPublic} from "../../services/user.js"

export default {
    components: {
        Message
    },
    route:{
        data({ to: { params: { conversationId } }}) {
            if (this.id !== conversationId){
                this.id = conversationId
            }
        }
    },
    data() {
        return {
            users: [],
            messages: [],
            typingText: "",
            clientId: 1,
            conversation: {},
            messageIterator: {},
            notiMemberId: "",
            id: "",
        }
    },
    init() {
        EventEmitter.on(IMClientInitEvent, ()=>{
            this.initConversation()
        })
        EventEmitter.on(MessageReciveEvent, (msg, conv) => {
            if (this.conversation && (conv.id === this.conversation.id)) {
                this.messages.push(msg)
            }
        })
    },
    ready() {
        this.initConversation()
    },
    methods: {
        initConversation() {
            if (_.isEmpty(imclient)) {
                throw new Error("即时通信未链接")
                return
            }
            this.clientId = imclient.id
            if (this.id) {
                imclient.getConversation(this.id).then(conv => {
                    this.conversation = conv
                    this.notiMemberId = conv.notiMemberId
                    this.messageIterator = conv.createMessagesIterator({ limit: 10 })
                    this.onLoadEarlier()
                })
            }
        },
        // mapLCMessage(val) {
        //     return {
        //         _id: val.id,
        //         text: val._lctext,
        //         createdAt: val.timestamp,
        //         user: {
        //             _id: val.from,
        //             name: 'none',
        //             avatar: ''
        //         }
        //     }
        // },
        onLoadEarlier() {
            //this.setState({ isLoadingEarlier: true })
            this.messageIterator.next().then(result => {
                // _messages = _.orderBy(_messages, ['timestamp'], ['desc'])
                this.messages = _.union(this.messages, result.value)
                this.LoadUser()
            })
        },
        LoadUser() {
            this.renderUser()
            this.messages.forEach(msg => {
                if (!_.find(this.users, { 'id': msg.from })) {
                    UserPublic({id: msg.from}).then(user => {
                        this.users.push(user.result)
                        this.renderUser()
                    })
                }
            })
        },
        renderUser() {
            this.messages = this.messages.map(msg => {
                if (!msg.name) {
                    let user = _.find(this.users, { 'id': msg.from })
                    if (user) {
                        let _msg = _.clone(msg)
                        _msg.name = user.nickName
                        _msg.avatar = user.avatarUrl ? user.avatarUrl: DEFAULT_AVATOR
                        return _msg
                    }
                }
                return msg
            })
        },
        onSend() {
            if (this.typingText === '') return
            this.conversation.send(new TextMessage(this.typingText)).then(msg => {
                this.messages.push(msg)
                this.LoadUser([msg])
                this.$els.input.value = ''
                this.typingText = ''
            }).catch((e) => {
                Toast.show('IM通信错误','warn')
            })
        }
    }
}
</script>

<style lang='sass'>
    .conversation-bg {
        background-color: #F5F5F5;
        .chat-body{
            margin-top: 48px;
        }
        .message-edit{
            display: flex;
            position: fixed;
            bottom: 0;
            width: 100%;
            max-width: 640px;
            justify-content: space-between;
            align-items: center;
            .message-input{
                height: 40px;
                flex: 2;
                border: solid 1px #fff;
                border-radius: 5px;
                font-size: 15px;
                margin-top: 20px;
                padding-left: 10px;
                outline: none;
            }
        }
    }
</style>